package com.example.callcenter.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.callcenter.dto.CustomerDTO;
import com.example.callcenter.entity.Customer;
import com.example.callcenter.mapper.CustomerMapper;
import com.example.callcenter.service.CustomerService;
import com.example.callcenter.util.UserContext;
import com.example.callcenter.util.ExcelUtil;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Override
    // 添加缓存注解，将新增客户存入缓存
    @CachePut(value = "customerCache", key = "#result.id")
    public Customer addCustomer(CustomerDTO customerDTO) {
        Customer customer = new Customer();
        customer.setName(customerDTO.getName());
        customer.setPhone(customerDTO.getPhone());

        customer.setCreateUserId(UserContext.getUserId());
//      冗余 本来就是null  customer.setId(customer.getId());

        customer.setCreateTime(LocalDateTime.now());
        baseMapper.insert(customer); // MyBatis-Plus会自动回填ID
        System.out.println("返回前id: " + customer.getId()); // 如果为null，说明getter有问题
        return customer; // 返回对象用于缓存

    }

    @Override
    public int importExcel(MultipartFile file) {
        List<CustomerDTO> list = ExcelUtil.readExcel(file, CustomerDTO.class);
        List<Customer> customers = list.stream().map(dto -> {
            Customer customer = new Customer();
            customer.setName(dto.getName());
            customer.setPhone(dto.getPhone());
            customer.setCreateUserId(UserContext.getUserId());
            customer.setCreateTime(LocalDateTime.now());
            return customer;
        }).collect(java.util.stream.Collectors.toList());
        saveBatch(customers);
        return customers.size();
    }
}